<?php


namespace app\api\controller\v26;


use app\api\controller\v2\Auth;
use app\common\cachemodel\MentalOptionModel;
use app\common\cachemodel\MentalQuestionModel;
use app\common\cachemodel\MentalUserRecordModel;
use app\common\cachemodel\Orders;
use app\common\lib\exception\ApiException;
use app\common\lib\MentalTestUtil;
use app\common\lib\SensorsData;
use Exception;
use think\Db;
use think\Env;
use think\Log;
use think\response\Json;
use XznsTools\cache\CacheManage;

class MentalTest extends Auth
{

    protected $domain_wap = '';
    protected $domain = '';
    private $LOG_PRE = 'MentalTest';

    public function _initialize()
    {
        parent::_initialize();
        $this->domain_wap = Env::get('host.wap_domain');
        $this->domain = Env::get('host.domain');
    }


    /**
     * 把app里的header里的内容通过参数传到webview里
     */
    public function redirectUrl()
    {
        $headers = request()->header();
        $h = input('h/d', 0);
        $page = input('page/s', '');

//        请求前缀：$HOST/api/v26/mental_test/index?zhunle_not_show_nav=1&h=【int 状态栏高度，参考意见反馈的参数】&need_auth=2【必须登录】
//问题列表：
//&page=mental_test_list&cid=【int 分类 分类 [0, 1, 2, 3, 4, 5]=》['精选', '情感', '人际', '职场', '健康', '性格']】&sort=【int 排序=》['默认', '按热度倒序', '按价格倒序', '只看付费', '只看免费']】
//问题详情：
//&page=mental_test_detail?id=【int 问题id】
//我的测评：
//&page=mental_test_mine?type=【int 0 未完成 1已完成】
//测评结果页：
//&page=mental_test_result?qid=【int 问题id】&child_id=【int 问题版本id（可以为空）】& order_id【string 订单id】
        $params_str = '';
        switch ($page)
        {
            case 'mental_test_list':
            {
                $params_str = 'page=' . $page;
                $cid = input('cid/d', 0);
                if ($cid >= 0)
                {
                    $params_str .= '&cid=' . $cid;
                }
                $sort = input('sort/d', 0);
                if ($sort >= 0)
                {
                    $params_str .= '&sort=' . $sort;
                }
                break;
            }
            case 'mental_test_detail':
            {
                $id = input('id/d', 0);
                if ($id >= 0)
                {
                    $params_str = 'page=' . $page . '&id=' . $id;
                }
                break;
            }
            case 'mental_test_mine':
            {
                $type = input('type/d', 0);
                if ($type >= 0)
                {
                    $params_str = 'page=' . $page . '&type=' . $type;
                }
                break;
            }
            case 'mental_test_result':
            {
                $qid = input('qid/d', 0);
                $child_id = input('child_id/d', 0);
                $order_id = input('order_id/s', '');
                $params = request()->param();
                if ($params)
                {
                    $order_id = $params['order_id'];
                }
                if ($qid)
                {
                    $params_str .= 'qid=' . $qid;
                }
                if ($child_id)
                {
                    $params_str .= '&child_id=' . $child_id;
                }
                if ($order_id)
                {
                    $params_str .= '&order_id=' . $order_id;
                }
                $url = $this->domain . '/api/v26/mental_test/result?' . $params_str . '&zhunle_not_show_nav=0&h=' . $h;
                $this->redirect($url);
            }

        }

        if ('' !== $params_str)
        {
            $params_str .= '&';
        }

        $url = $this->domain_wap . '/zhunle_wap_yixinli?' . $params_str . 'token=' . $headers['access-token'] . '&app_type=' . $headers['app-type'] . '&did=' . $headers['did'] . '&model=' . $headers['model'] . '&sign=' . $headers['sign'] . '&time=' . $headers['time'] . '&version=' . $headers['version'] . '&phone_version=' . $headers['phone-version'] . '&h=' . $h;
        //http://192.168.0.193:8088/zhunle_wap_yixinli?token=+j193+Bv4MUkRfHPfpFsYvFZJ//Yxa04IiCqHYK2XDH3A5haG2gnRNZDx6qohQnluP00gJGgRTjWOuS3Zw99tA==&app_type=ios&did=7CF2CE33-9E2C-4CE1-948E-1D1245AA91D4&model=iPhone 7 Plus&sign=KkzHDPmQm+bVGlH9DqB6WsHF1SQSKrSjSpI0ZpszA+oCFws957NPME+c9lWECBkKv/DBH2Xs9rAQm9PHfu8eMSfwY+qMzJopq/Swzr+u121SeAi+dxNpaPDT8VUpL0drrCdq7T2RALq9Nn/n7JhtPwkhl5p+HtMYRU/wuVm4k17rMv4ORRZJVuu07gh/HNQN&time=1619685277&version=2.5.5&phone_version=ios:12.4.1&h=20
        //https://beta-wap.goddessxzns.com/zhunle_wap_yixinli?token=+j193+Bv4MUkRfHPfpFsYvFZJ//Yxa04IiCqHYK2XDH3A5haG2gnRNZDx6qohQnluP00gJGgRTjWOuS3Zw99tA==&app_type=ios&did=7CF2CE33-9E2C-4CE1-948E-1D1245AA91D4&model=iPhone 7 Plus&sign=KkzHDPmQm+bVGlH9DqB6WsHF1SQSKrSjSpI0ZpszA+oCFws957NPME+c9lWECBkKv/DBH2Xs9rAQm9PHfu8eMSfwY+qMzJopq/Swzr+u121SeAi+dxNpaPDT8VUpL0drrCdq7T2RALq9Nn/n7JhtPwkhl5p+HtMYRU/wuVm4k17rMv4ORRZJVuu07gh/HNQN&time=1619685277&version=2.5.5&phone_version=ios:12.4.1&h=20
        $this->redirect($url);
    }

    /**
     * 获取心理测试列表
     * @return Json
     * @throws Exception
     */
    public function getQuestionList(): Json
    {
        $params_category = input('category/d', 0);//分类
        $params_sort = input('sort/d', 0);//排序
        $params_page = input('page/d', 0);//排序

        $data = (new MentalQuestionModel())->getQuestionList($params_category, $params_sort, $params_page);
        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 获取问题详情
     * @throws Exception
     */
    public function getQuestionDetail()
    {
        $id = input('id/d', 0);

        $mentalQuestionModel = new MentalQuestionModel();
        $detail = $mentalQuestionModel->getQuestionDetailById($id);
        if ($detail['child_scales'])
        {
            $detail['child_scales'] = json_decode($detail['child_scales'], true);
        }
        $recommends = $mentalQuestionModel->getRecommondQuestions($detail['ocategory'], 3);

        if ($detail)
        {
            if (isset($detail['pure_detail_desc']))
            {
//                ① 本测评为付费测试，测试时间需 8-15 分钟。② 付费成功后将自动跳转到答题页，由于题目数较多，可能需要几秒进行加载，建议在网络较好的情况下测试。③ 为保证准确性，测评不能重复测试，请根据实际情况作答，答题结束后会生成一份专业的测评报告。④ 购买的测评均永久保存在网站底部菜单「我的测评」中，进入即可继续答题或查看报告。
                $detail['pure_detail_desc'] = str_replace(['购买的测评均永久保存在网站底部菜单', '②', '③', '④', '⑤'], ['购买的测评均永久保存在', '</br>②', '</br>③', '</br>④', '</br>⑤'], $detail['pure_detail_desc']);
            }

//            $detail['is_not_pay_can_test'] = (int)config('mental_test.is_not_pay_can_test');
            return show(config('code.success'), '请求成功', ['detail' => $detail, 'recommends' => $recommends]);
        }
        return show(config('code.error'), '数据不存在');
    }

    /**
     * 支付接口
     * @return Json
     * @throws Exception
     */
    public function pay(): ?Json
    {
        $trade_type = input('trade_type/d', 0);//2=>支付宝,1=>微信支付
        $qid = input('qid/d', 0);//问题id
        $child_id = input('child_id/d', 0);//解锁id
        $params_is_confirm_pay = input('is_confirm_pay/d', 0);//是否确认支付

        //校验参数
        if (!in_array($trade_type, [1, 2], true))
        {//1=>支付宝,2=>微信支付
            return show(config('code.error'), '支付方式错误！');
        }
        if (!$qid)
        {
            return show(config('code.error'), '问题id错误！');
        }


        //校验问题 是否与 解锁id 一致
        $mentalQuestionModel = new MentalQuestionModel();
        $question = $mentalQuestionModel->getQuestionDetailById($qid, ['id', 'name', 'ocategory', 'child_scales', 'price_discount', 'oid', 'type']);

        if (!$question)
        {
            return show(config('code.error'), '测评问题不存在！');
        }

        $valids = MentalTestUtil::validChildId($question, $child_id);
        if (!$valids[0])
        {
            return show(config('code.error'), '问题id和解锁id不一致！');
        }

        //先通过壹心理接口，生成支付信息
        $out_trade_no = date('YmdHis') . str_pad(random_int(1, 99), 2, '0', STR_PAD_LEFT);
        if (1 === (int)$question['type'])
        {//免费的问题直接下单
            $account_id_free = MentalTestUtil::payFree($this->user['id'], $out_trade_no, $child_id ?: $question['oid']);
            return show(config('code.success'), '下单成功！', ['account_id_free' => $account_id_free]);
        }

        if (!$params_is_confirm_pay)
        {//不是确认支付，检查 用户之前购买过同样的问题
            $payed_question = (new MentalUserRecordModel())->getUserRecentRecord($this->user['id'], $qid, $child_id);
            if ($payed_question)
            {
                //status 答题状态 0=> 未开始，1=> 未完成，2=> 已完成
                $data = [
                    'status' => (int)$payed_question['status'],
                    'qid' => (int)$payed_question['qid'],
                    'child_id' => (int)$payed_question['child_id'],
                    'order_id' => (int)$payed_question['order_id'],
                ];
                if ((int)$payed_question['status'] === 2)
                {
                    $data['hint'] = '亲，该测评您于' . date('Y年m月d日H:i:s', $payed_question['create_time']) . '买过，是否确定再次购买？（重复支付不予退款）';
                } else
                {
                    $data['hint'] = '亲，该测评您有未完成记录，是否继续答题？';
                }
                return show(config('code.success'), '请求成功！', $data);
            }
        }

        $pay_info = MentalTestUtil::pay($this->user['id'], $out_trade_no, $child_id ?: $question['oid'], $trade_type);

        //订单入库
        Db::startTrans();
        try
        {
            $insert = [
                'order_type' => 18,
                'uid' => $this->user['id'],
                'gid' => $qid,
                'order_id' => $out_trade_no,
                'reid' => 0,
                'fid' => 0,
                'trade_type' => (1 === $trade_type ? 2 : 1),//1=>支付宝,2=>微信支付
                'total_amount' => $question['price_discount'],
                'create_time' => time(),
                'status' => 2,
                'account' => 0,
                'extend' => $child_id ?: ''
            ];
            $orderCacheModel = new Orders();
            $orderCacheModel->SaveData($insert);
            Db::commit();
        }
        catch (Exception $e)
        {
            Db::rollback();
            Log::write('心理测试下单失败：' . $e->getMessage(), 'error');
            throw new ApiException('下单失败,请重新操作');
        }

        try
        {
            #神策打点 104 心理测评确认订单 MentalTestBuy
            $sensorsTrackData = [
                'test_id' => $qid,// 测评ID NUMBER
                'test_name' => $question['name'],// 测评名称 STRING
                'test_category' => $question['ocategory'],// 测评分类 STRING
                'test_child_id' => (int)$child_id,// 测评版本ID NUMBER
                'test_child_name' => $valids[1]['name'] ?? '',// 测评版本名称 NUMBER
                'total_amount' => $question['price_discount'],// 实付价格 NUMBER
                'order_id' => $out_trade_no,// 订单编号 STRING
                'trade_type' => $insert['trade_type'],// 支付方式 NUMBER
                'is_success' => true,// 是否成功 BOOL
                'failed_reson' => '',// 失败原因 STRING
            ];

            SensorsData::track($this->user['id'], true, 'MentalTestBuy', $sensorsTrackData);
        }
        catch (Exception $e)
        {
            Log::write('神策打点-104-心理测评确认订单打点失败：' . $e->getMessage() . '[' . $e->getFile() . ':' . $e->getLine() . ']', 'error');
        }

        return show(config('code.success'), '下单成功！', $pay_info);
    }


    /**
     * 支付接口
     * @return Json
     * @throws Exception
     */
    public function getPayResult(): ?Json
    {
        $order_id = input('order_id/s', '');
        $qid = input('qid/s', 0);
        $child_id = input('child_id/d', 0);//解锁id（有可能为空）


        if (!$order_id)
        {
            return show(config('code.error'), '订单号错误！');
        }
        if (!$qid)
        {
            return show(config('code.error'), '问题id错误！');
        }

        //校验问题 是否与 解锁id 一致
        $question = (new MentalQuestionModel())->getQuestionDetailById($qid, ['id', 'name', 'ocategory', 'child_scales', 'price_discount']);
        if (!$question)
        {
            return show(config('code.error'), '测评问题不存在！');
        }

        $valids = MentalTestUtil::validChildId($question, $child_id);

        if (!$valids[0])
        {
            return show(config('code.error'), '问题id和解锁id不一致！');
        }


        //查询壹心理接口，订单是否已完成
        $result = MentalTestUtil::queryOrder($order_id);
        if ($result['is_sucess'])
        {
            $orderCacheModel = new Orders();
            //查询订单表，订单是否已完成
            $order = $orderCacheModel->getInfoById($order_id);
            if ($order && 4 === (int)$order['status'])
            {
                $is_sucess = true;
            } else
            {//插入数据
                try
                {
                    Db::startTrans();
                    //更新订单状态
                    $orderCacheModel = new Orders();
                    $is_sucess = $orderCacheModel->UpdateData($order_id, ['status' => 4], 4);
                    //新增测评记录
                    (new MentalUserRecordModel())->saveData([
                        'uid' => $this->user['id'],
                        'qid' => $qid,
                        'child_id' => $child_id,
                        'order_id' => $order_id,
                        'account_id' => $result['account_id'],
                        'create_time' => time(),
                    ]);
                    Db::commit();
                }
                catch (Exception $e)
                {
                    Db::rollback();
                    Log::write('心理测试查询订单失败：' . $e->getMessage(), 'error');
                    throw new ApiException('支付失败！');
                }

                try
                {
                    #神策打点 105 心理测评支付成功 MentalTestBuySuccess
                    $sensorsTrackData = [
                        'test_id' => (int)$qid,// 测评ID NUMBER
                        'test_name' => $question['name'],// 测评名称 STRING
                        'test_category' => $question['ocategory'],// 测评分类 STRING
                        'test_child_id' => (int)$child_id,// 测评版本ID NUMBER
                        'test_child_name' => $valids[1]['name'] ?? '',// 测评版本名称 NUMBER
                        'total_amount' => $order['total_amount'],// 实付价格 NUMBER
                        'order_id' => $order_id,// 订单编号 STRING
                        'trade_type' => (int)$order['trade_type'],// 支付方式 NUMBER
                        'is_success' => true,// 是否成功 BOOL
                        'failed_reson' => '',// 失败原因 STRING
                    ];

                    SensorsData::track($this->user['id'], true, 'MentalTestBuySuccess', $sensorsTrackData);
                }
                catch (Exception $e)
                {
                    Log::write('神策打点-105-心理测评支付成功打点失败：' . $e->getMessage() . '[' . $e->getFile() . ':' . $e->getLine() . ']', 'error');
                }
            }

            if ($is_sucess)
            {
                return show(config('code.success'), '支付成功！', ['qid' => $qid, 'child_id' => $child_id]);
            }

            return show(config('code.error'), '查询失败！');
        }

        return show(config('code.error'), '支付失败！');
    }

    /**
     * 获取问题的所有选项
     * @return Json
     * @throws Exception
     */
    public function getOptionList(): ?Json
    {
        $qid = input('qid/d', 0);//问题id
        $child_id = input('child_id/d', 0);//子类id
        $order_id = input('order_id/s', '');
        if (!$qid)
        {
            return show(config('code.error'), '问题id错误！');
        }

        //获取问题详情
        $mentalQuestionModel = new MentalQuestionModel();
        $question = $mentalQuestionModel->getQuestionDetailById($qid, ['id', 'online_type', 'type', 'name', 'detail_desc', 'child_scales']);

        if (!$question)
        {
            return show(config('code.error'), '测评问题不存在！');
        }

        $valids = MentalTestUtil::validChildId($question, $child_id);

        if (!$valids[0])
        {
            return show(config('code.error'), '问题id和解锁id不一致！');
        }


        if ($valids[1])
        {
            $qid = $valids[1]['id'];
            $question = $valids[1];
        }

        if ((int)$question['type'] === 2)
        {//付费
            //查询测评记录
            $mentalUserRecordModel = new MentalUserRecordModel();
            $user_record_detail = $mentalUserRecordModel->getUserRecrodDetail($this->user['id'], $order_id);
            //查询订单表里是否购买成功
            $ordersModel = new Orders();
            $orders = $ordersModel->getInfoById($user_record_detail['order_id']);

            if ((int)$orders['status'] === 4 || config('mental_test.is_not_pay_can_test'))
            {//购买成功，返回数据
                $questions = (new MentalOptionModel())->getOptionList($qid);
                //删除最近的答题记录缓存，防止用户不答题，点击返回，没有更新缓存
                CacheManage::getInstance()->setCacheConfig('mental_test.recent', $this->user['id'] . ':' . $qid . ':' . $child_id)->rmCache();
            } else
            {//购买失败，提示信息
                return show(config('code.error'), '您尚未购买！');
            }

            if (!$user_record_detail)
            {//不存在测评记录，那么新增
                $mentalUserRecordModel->saveData([
                    'uid' => $this->user['id'],
                    'qid' => $qid,
                    'child' => $child_id,
                    'order_id' => $order_id
                ]);
            }
        } else
        {//免费
            $questions = (new MentalOptionModel())->getOptionList($qid);
        }

        if (!empty($questions))
        {
            //hint进行替换
            $hint = $question['detail_desc'];
            $hint = str_replace(['3. 如遇电话、死机等导致测试中断，可到公众号找回，系统将保留你的答题记录。', '购买的测评均永久保存在网站底部菜单', '（右上方有时间进度条）', 'rgb(0, 0, 0)', 'background-color: rgb(255, 204, 0);', 'background-color: #ffcc00;'], ['', '购买的测评均永久保存在', '', 'rgba(0, 216, 211)', '', ''], $hint);

            return show(config('code.success'), '请求成功', [
                'detail' => [
                    'id' => $qid,
                    'name' => $question['name'],
                    'type' => (int)$question['type'],
                    'hint' => $hint
                ],
                'questions' => $questions,
                'answer_content' => (!isset($user_record_detail['answer_content']) || $user_record_detail['answer_content'] === '') ? [] : json_decode($user_record_detail['answer_content'], true)
            ]);
        }

        Log::write('问题列表为空：【qid=' . $qid . ',child_id=' . $child_id . ',order_id=' . $order_id . '】', 'error');
        return show(config('code.error'), '问题列表为空！');
    }

    /**
     * 获取我的测评列表
     * @return Json
     * @throws Exception
     */
    public function getHistoryRecords(): Json
    {
        $params_status = input('status/d', 1);//分类 1：未完成；2：已完成
        if (!in_array($params_status, [1, 2], true))
        {
            return show(config('code.error'), '参数错误！');
        }

        $data = (new MentalUserRecordModel())->getRecordList($this->user['id'], $params_status);
        return show(config('code.success'), '请求成功', $data);
    }


    /**
     * 提交答案
     * @return Json
     * @throws Exception
     */
    public function submitAnswer(): Json
    {
        $params_type = input('type/d', 0);//类型：0=》未答完题，保存答题进度；1=》已经答完题了
        $params_qid = input('qid/d', 0);
        $params_order_id = (int)input('order_id/s', '');
        $params_child_id = input('child_id/d', 0);//子类id
        $params_answer_content = input('answer_content/a', []);
        $params_account_id_free = input('account_id_free/d', 0);//免费的问题才有这个参数
        //校验参数
        if (!in_array($params_type, [0, 1], true))
        {
            return show(config('code.error'), 'type参数错误！');
        }
        if (!$params_qid)
        {
            return show(config('code.error'), '问题参数错误！');
        }
        if (count($params_answer_content) === 0)
        {
            return show(config('code.error'), '答案为空！');
        }

        //校验问题id
        $mentalQuestionModel = new MentalQuestionModel();
        $question = $mentalQuestionModel->getQuestionDetailById($params_qid, ['id', 'online_type', 'oid', 'type', 'name', 'detail_desc', 'child_scales']);
        if (!$question)
        {
            return show(config('code.error'), '测评问题不存在！');
        }

        $valids = MentalTestUtil::validChildId($question, $params_child_id);

        if (!$valids[0])
        {
            return show(config('code.error'), '问题id和解锁id不一致！');
        }

        if (0 === $params_account_id_free)
        {//付费的问题，才保存进度，免费的问题不保存进度
            //校验用户是否存在测评记录
            $mentalUserRecordModel = new MentalUserRecordModel();
            $userRecrodDetail = $mentalUserRecordModel->getUserRecrodDetail($this->user['id'], $params_order_id);
            if (!$userRecrodDetail)
            {
                return show(config('code.error'), '用户答题记录为空！');
            }

            //记录入库数据
            $data = [
                'id' => $userRecrodDetail['id'],
                'uid' => $this->user['id'],
                'qid' => $params_qid,
                'child_id' => $params_child_id,
                'order_id' => $params_order_id,
                'answer_content' => json_encode($params_answer_content),
            ];

            if (0 === $params_type)
            {//保存进度
                $data['status'] = 1;//答题状态 1=> 未完成，2=> 已完成
                //免费的题 不保存答题进度
                //保存答案数据
                $is_save_answer_ok = $mentalUserRecordModel->updateData($data);
                if ($is_save_answer_ok)
                {
                    return show(config('code.success'), '保存进度成功！');
                }
                Log::write('免费测评，' . ($is_save_answer_ok ? '' : '保存进度') . '失败[uid=' . $this->user['id'] . ',qid=' . $params_qid . ',child_id=' . $params_child_id . ',type=' . $params_type . ',answer_content=' . json_encode($params_answer_content, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ']', 'error', true);
                return show(config('code.error'), '保存进度失败！');
            }
        }

        //order_id不为空，结果地址为空，那么去 查询是否已经购买成功了
//        if (isset($userRecrodDetail['order_id']) && $userRecrodDetail['order_id'] && $params_order_id)
//        {
//            //结果地址
//            $result = MentalTestUtil::getReportUrl((int)$userRecrodDetail['account_id']);
//            if ($result[0])
//            {//保存结果地址
//                $data['result_url'] = $result[1];
//                $data['status'] = 2;
//                $is_save_answer_ok = $mentalUserRecordModel->updateData($data);
//                if ($is_save_answer_ok)
//                {
//                    return show(config('code.success'), '请求成功', [
//                        'qid' => $params_qid,
//                        'child_id' => $valids[1] ? (int)$valids[1]['oid'] : '',
//                        'order_id' => $userRecrodDetail['order_id'],
//                    ]);
//                }
//            }
//        }


        if (1 === $params_type)
        {//提交答案
            //检查答案数量是否与服务器一致
            $qid = $valids[1] ? (int)$valids[1]['id'] : $params_qid;
            $questions = (new MentalOptionModel())->getOptionList($qid);

            if (count($params_answer_content) !== count($questions))
            {
                Log::write($this->LOG_PRE . '您的答案数量错误，请重新答题！[type=' . $params_type . 'qid=' . $params_qid . 'child_id=' . $params_child_id . 'answer_content=' . json_encode($params_answer_content, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ']', 'error', true);
                return show(config('code.error'), '您的答案数量错误，请重新答题！');
            }

            //壹心理，提交答案
            $answers = [];
            $questionnaireId = $valids[1] ? (int)$valids[1]['oid'] : $question['oid'];
            if ((int)$questionnaireId === 353)
            {//由于壹心理改题了，所以要修改这里，只有这一个有问题，其他的不影响
                $questionnaireId = 563;
            }

            foreach ($questions as $k => $v)
            {
                //type 选项类型：【1=》问题；2=》选项；】
                if ($v['type'] === 1)
                {
                    $answers['answers[' . $k . '][questionnaireId]'] = (int)$questionnaireId;
                    $answers['answers[' . $k . '][questionId]'] = (int)$v['oid'];
                    $answers['answers[' . $k . '][type]'] = (int)$v['option_type'];

                    //问题类型 0选项题，1游标题，2文字题
                    if (0 === (int)$v['option_type'])
                    {
//                        foreach ($v['options'] as $oK => $oV)
//                        {
//                            if (trim($params_answer_content[$k]) === trim($oV['label']))
//                            {
                        $oV = $v['options'][$params_answer_content[$k]];//改为index模式，因为上面的校验，里面label存在  ◆  ♦的情况
                        $answers['answers[' . $k . '][optionId]'] = (int)$oV['oid'];
                        if (isset($oV['score']))
                        {//如果选择题里的score不为空，也传过去
                            $answers['answers[' . $k . '][score]'] = $oV['score'];
                        }
//                            }
//                        }
                    } else if (1 === (int)$v['option_type'])
                    {//| score  | false      |   int    |	游标题得分。|
                        $answers['answers[' . $k . '][score]'] = (float)$params_answer_content[$k];
                        $answers['answers[' . $k . '][optionId]'] = (int)$v['oid'];
                    } else if (2 === (int)$v['option_type'])
                    {//| content  | false      |   string    |	文本题内容，长度不限制。|
                        $answers['answers[' . $k . '][content]'] = $params_answer_content[$k];
                        $answers['answers[' . $k . '][optionId]'] = (int)$v['oid'];
                    }
                }
            }
            if (count($questions) !== count($params_answer_content))
            {
                Log::write('付费测评，提交答案校验失败，【问题数量：' . count($questions) . '，答案数量：' . count($params_answer_content) . '】[uid=' . $this->user['id'] . ',qid=' . $params_qid . ',child_id=' . $params_child_id . ',type=' . $params_type . 'answer_content=' . json_encode($params_answer_content, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ']', 'error', true);
            }

            if (1 === (int)$question['type'])
            {//免费的问题，提交答案
                $submit_result = MentalTestUtil::submitAnswers($params_account_id_free, $answers);
            } else
            {//付费的问题，提交答案
                $submit_result = MentalTestUtil::submitAnswers($userRecrodDetail['account_id'], $answers);
            }
//            return show(config('code.error'), '提交失败！');//test
            //保存答案数据
            if ($submit_result[0])
            {
                $data['status'] = 2;//答题状态 1=> 未完成，2=> 已完成
                $data['result_url'] = $submit_result[1];

                if ($params_account_id_free)
                {//如果是免费的问题，直接返回结果
                    return show(config('code.success'), '提交成功！', $data);
                }

                //如果是付费的问题，更新数据（答题状态和结果地址）
                $is_save_answer_ok = (new MentalUserRecordModel())->updateData($data);
                if ($is_save_answer_ok)
                {
                    return show(config('code.success'), '提交成功！', [
                        'qid' => $params_qid,
                        'child_id' => $params_child_id,
                        'order_id' => $params_order_id,
                    ]);
                }
            }

            Log::write('付费测评，' . ($params_type === 0 ? '提交答案' : '') . ($params_type === 0 ? '保存进度' : '') . '失败[uid=' . $this->user['id'] . ',qid=' . $params_qid . ',child_id=' . $params_child_id . ',type=' . $params_type . ',answer_content=' . json_encode($params_answer_content, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ']', 'error', true);

            return show(config('code.error'), '提交失败！');

        }

        return show(config('code.error'), '提交失败！');
    }


    /**
     * 跳转到结果页
     * @throws Exception
     */
    public function redirectResultUrl()
    {
        $params_qid = input('qid/d', 0);
        $params_child_id = input('child_id/d', 0);//子类id
        $params_order_id = input('order_id/s', '');

        if (!$params_qid)
        {
            return show(config('code.error'), '问题id不能为空！');
        }
        if (!$params_order_id || strlen($params_order_id) !== 16)
        {
            return show(config('code.error'), '订单id异常！');
        }

        $uid = $this->user['id'];

        //校验问题id
        $mentalQuestionModel = new MentalQuestionModel();
        $question = $mentalQuestionModel->getQuestionDetailById($params_qid, ['id', 'online_type', 'oid', 'type', 'name', 'detail_desc', 'child_scales']);
        if (!$question)
        {
            return show(config('code.error'), '测评问题不存在！');
        }

        $valids = MentalTestUtil::validChildId($question, $params_child_id);

        if (!$valids[0])
        {
            return show(config('code.error'), '问题id和解锁id不一致！');
        }

        //校验用户是否存在测评记录
        $mentalUserRecordModel = new MentalUserRecordModel();
        $userRecrodDetail = $mentalUserRecordModel->getUserRecrodDetail($uid, $params_order_id);
        if (!$userRecrodDetail || !isset($userRecrodDetail['result_url']) || !$userRecrodDetail['result_url'])
        {
            Log::write('用户跳转到结果页异常：[qid=' . $params_qid . ',child_id=' . $params_child_id . ',order_id=' . $params_order_id . ',uid=' . $uid . ']', 'error', true);
            return show(config('code.error'), '答题结果页异常！');
        }

//        if ('android' === $this->headers['app-type'])
//        {
        return show(config('code.success'), '请求成功！', ['result_url' => $userRecrodDetail['result_url']]);
//        }

        //成功那么跳转到结果页地址
//        $this->redirect($userRecrodDetail['result_url']);
    }
}
